import laydate from 'laydate-es6';
import ajax from '../../utils/ajax';
import upload from '../../utils/upload';

const form = document.forms.userinfo;
const avatar = document.getElementById('avatar')

init();

async function init() {
    //初始化日历
    init_laydate()
    //默认数据填充到表单
    reset();
    //增加表单提交事件
    form.onsubmit = form_submit;
    //上传图片本地预览
    form.avatar.onchange= avatar_change
}


function init_laydate() {
    laydate.render({
        elem: "#birthday",
        max: '2023-1-5'
    })
}


 async function reset() {
    const { data } =await ajax('get', '/api/getUserInfo');
    console.log(data);
        if (data.nickname) {
            form.nickname.value = data.nickname
        }
        if (data.gender) {
            form.gender.value = data.gender.data[0]==0?'male':'female';
        }
        if (data.birthday) {
            form.birthday.value = data.birthday.slice(0,10);
        }
        if (data.avatar) {
            console.log(data.avatar);
            avatar.src ='http://127.0.0.1:3000' + data.avatar
        }
    } 

    
 function form_submit(e) {
    e.preventDefault();
//收集表单数据，以formdata形式
    const fd = new FormData(form)

    upload('/api/updateUserInfo',fd).then(result =>{
        if(result.flag){
            alert(result.msg)

        }
    })
}


//图片本地预览
function avatar_change(){
    // 把this指向固定到固定的变量之中
    const that = this;
    // 判断文件域有没有选择文件
    if(that.files.length > 0){
        //限定文件是图片
        if(!/^image\//.test(that.files[0].type)){
        alert('图片格式不正确');
        //如果不正确不能被选中
        that.value = null;
        avatar.src = ''
        return;
        }
        //限定图片尺寸
        if(that.files[0].size > 1024*1000){
            alert('图片大小不能超过200kb');
             //如果不正确不能被选中
            that.value = null;
            //清空
            avatar.src = '';
            return;
        }
        avatar.src = URL.createObjectURL(that.files[0])
    }else{
        avatar.src = ''
    }
}